(function () {
    var app;
    if(location.href.indexOf("producer") > -1){
        app = "producer";

    } else if(location.href.indexOf("delivery") > -1 ){
        app = "delivery";
    } else {
        console.log('外壳有问题');
    }
    function deleteCookie(name) {
        var cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        document.cookie = cookie;
    }

    function responseToJson(responsePromise) {
        return responsePromise.then(function (res) {
            if (res.ok) {
                return res && res.json();
            } else {
                throw new Error(res.statusText);
            }
        });
    }

    function getLocalVersion() {
        return responseToJson(fetch('./assets/version.json', { credentials: 'include' })).then((res) => {
            return res.version + "";
        })
    }

    function fetchRemoteUpgradeData(localVersion) {
        var store = localStorage.getItem("Store");
        var url = "";
        if (store) {
            store = JSON.parse(store);
            url = "/api/gray/release/webapp/" + "m"+app + "/upgrade?version=" + localVersion + "&storeId=" + store.id;
        } else {
            url = "/api/gray/release/webapp/" + "m"+app + "/upgrade?version=" + localVersion;
        }
        return responseToJson(fetch(url)).then((res) => {
            if (res.code != 200) {
                throw new Error(res);
            }
            return res.data;
        })
    }

    function getCurrVersion(localVersion) {
        return fetchRemoteUpgradeData(localVersion).then((data) => {
            return data.currVersion + "";
        })
    }

    function goUpdatePage() {
        location.href = "./boots/update.html";
    }

    function checkUpdate(localVersion, currVersion) {
        if (localVersion != currVersion ) {
            document.cookie = app +"CurrVersion=" + currVersion + "; expires=Thu, 01 Jan 2100 00:00:01 GMT;path=/";
            goUpdatePage();
        }
    }

    function startUpdate() {
        deleteCookie('from_version');
        getLocalVersion().then((localVersion) => {
            return getCurrVersion(localVersion).then((currVersion) => {
                return checkUpdate(localVersion, currVersion);
            })
        }).catch(ex => { console.log(ex) })
    }
    localStorage.getItem("needUpdated") === 'true' ? localStorage.setItem("needUpdated", false) : startUpdate();
})()